<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生数据库管理系统</title>
    <style>
        /* 样式保持不变，与之前相同 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .class-selector {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        
        .class-btn {
            padding: 12px 25px;
            margin: 0 10px;
            background-color: #fff;
            border: 2px solid #2575fc;
            border-radius: 30px;
            font-size: 1rem;
            font-weight: bold;
            color: #2575fc;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .class-btn.active {
            background-color: #2575fc;
            color: white;
        }
        
        .class-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .search-box {
            flex: 1;
            max-width: 400px;
            position: relative;
        }
        
        .search-box input {
            width: 100%;
            padding: 12px 20px;
            border: 2px solid #ddd;
            border-radius: 30px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .search-box input:focus {
            border-color: #2575fc;
            outline: none;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 12px 20px;
            background-color: #2575fc;
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            background-color: #1a68e3;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .btn-secondary {
            background-color: #6c757d;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .btn-success {
            background-color: #28a745;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-danger {
            background-color: #dc3545;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .table-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background-color: #f8f9fa;
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }
        
        th {
            font-weight: 600;
            color: #495057;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.2s;
        }
        
        .edit-btn {
            background-color: #ffc107;
            color: #212529;
        }
        
        .edit-btn:hover {
            background-color: #e0a800;
        }
        
        .delete-btn {
            background-color: #dc3545;
            color: white;
        }
        
        .delete-btn:hover {
            background-color: #c82333;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-title {
            font-size: 1.5rem;
            font-weight: bold;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #6c757d;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }
        
        .form-group input:focus {
            border-color: #2575fc;
            outline: none;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        
        .stats {
            display: flex;
            justify-content: space-around;
            margin-top: 30px;
            flex-wrap: wrap;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            text-align: center;
            flex: 1;
            min-width: 200px;
            margin: 10px;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #2575fc;
            margin: 10px 0;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 1rem;
        }
        
        footer {
            text-align: center;
            margin-top: 40px;
            padding: 20px;
            color: #6c757d;
            border-top: 1px solid #e9ecef;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }
        
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-box {
                max-width: 100%;
            }
            
            th, td {
                padding: 10px;
            }
            
            .actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>学生数据库管理系统</h1>
            <p class="description">数字媒体技术1班和2班学生信息管理</p>
        </header>
        
        <div id="errorMessage" class="error-message" style="display: none;"></div>
        
        <div class="class-selector">
            <button class="class-btn active" data-class="1">数字媒体技术1班</button>
            <button class="class-btn" data-class="2">数字媒体技术2班</button>
        </div>
        
        <div class="controls">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="搜索学生姓名或学号...">
            </div>
            <div class="action-buttons">
                <button class="btn btn-secondary" id="refreshBtn">刷新数据</button>
                <button class="btn btn-success" id="addStudentBtn">添加学生</button>
            </div>
        </div>
        
        <div class="table-container">
            <table id="studentTable">
                <thead>
                    <tr>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>作业主页</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="studentTableBody">
                    <tr>
                        <td colspan="4" class="loading">正在加载学生数据...</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-label">当前班级学生总数</div>
                <div class="stat-value" id="totalStudents">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">已填写主页学生</div>
                <div class="stat-value" id="withHomepage">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">未填写主页学生</div>
                <div class="stat-value" id="withoutHomepage">0</div>
            </div>
        </div>
        
        <footer>
            <p>学生数据库管理系统 &copy; 2023 | 使用HTML5 + JavaScript + PHP开发</p>
        </footer>
    </div>
    
    <!-- 添加/编辑学生模态框 -->
    <div class="modal" id="studentModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">添加学生</h2>
                <button class="close-btn" id="closeModal">&times;</button>
            </div>
            <form id="studentForm">
                <div class="form-group">
                    <label for="studentId">学号</label>
                    <input type="text" id="studentId" required>
                </div>
                <div class="form-group">
                    <label for="studentName">姓名</label>
                    <input type="text" id="studentName" required>
                </div>
                <div class="form-group">
                    <label for="homepage">作业主页 (URL)</label>
                    <input type="text" id="homepage">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="cancelBtn">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // API基础URL - 根据您的实际部署路径修改
        const API_BASE_URL = 'http://8.136.185.202/students_api.php';
        
        // 应用程序状态
        let currentClass = 1;
        let students = [];
        let editingStudent = null;

        // DOM元素
        const classButtons = document.querySelectorAll('.class-btn');
        const studentTableBody = document.getElementById('studentTableBody');
        const searchInput = document.getElementById('searchInput');
        const refreshBtn = document.getElementById('refreshBtn');
        const addStudentBtn = document.getElementById('addStudentBtn');
        const studentModal = document.getElementById('studentModal');
        const closeModal = document.getElementById('closeModal');
        const cancelBtn = document.getElementById('cancelBtn');
        const studentForm = document.getElementById('studentForm');
        const modalTitle = document.getElementById('modalTitle');
        const totalStudentsEl = document.getElementById('totalStudents');
        const withHomepageEl = document.getElementById('withHomepage');
        const withoutHomepageEl = document.getElementById('withoutHomepage');
        const errorMessageEl = document.getElementById('errorMessage');

        // 显示错误信息
        function showError(message) {
            errorMessageEl.textContent = message;
            errorMessageEl.style.display = 'block';
            setTimeout(() => {
                errorMessageEl.style.display = 'none';
            }, 5000);
        }

        // 从服务器获取学生数据
        async function fetchStudents(classId) {
            try {
                studentTableBody.innerHTML = '<tr><td colspan="4" class="loading">正在加载学生数据...</td></tr>';
                
                const response = await fetch(`${API_BASE_URL}/students_api.php?class=${classId}`);
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '获取学生数据失败');
                }
                
                if (result.success) {
                    return result.data;
                } else {
                    throw new Error(result.error || '获取学生数据失败');
                }
            } catch (error) {
                console.error('获取学生数据失败:', error);
                studentTableBody.innerHTML = `<tr><td colspan="4" class="loading" style="color: #dc3545;">加载失败: ${error.message}</td></tr>`;
                showError(`加载学生数据失败: ${error.message}`);
                return [];
            }
        }
        
        // 添加学生到数据库
        async function addStudent(student) {
            try {
                const response = await fetch(`${API_BASE_URL}/students_api.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(student)
                });
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '添加学生失败');
                }
                
                return result.success;
            } catch (error) {
                console.error('添加学生失败:', error);
                showError(`添加学生失败: ${error.message}`);
                return false;
            }
        }
        
        // 更新学生信息
        async function updateStudent(student) {
            try {
                const response = await fetch(`${API_BASE_URL}/students_api.php`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(student)
                });
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '更新学生信息失败');
                }
                
                return result.success;
            } catch (error) {
                console.error('更新学生信息失败:', error);
                showError(`更新学生信息失败: ${error.message}`);
                return false;
            }
        }
        
        // 删除学生
        async function deleteStudent(studentId, classId) {
            try {
                const response = await fetch(`${API_BASE_URL}/students_api.php`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: studentId,
                        class: classId
                    })
                });
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '删除学生失败');
                }
                
                return result.success;
            } catch (error) {
                console.error('删除学生失败:', error);
                showError(`删除学生失败: ${error.message}`);
                return false;
            }
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', async () => {
            // 初始加载学生数据
            students = await fetchStudents(currentClass);
            renderStudentTable();
            updateStats();
            
            // 班级切换事件
            classButtons.forEach(btn => {
                btn.addEventListener('click', async () => {
                    classButtons.forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    currentClass = parseInt(btn.getAttribute('data-class'));
                    students = await fetchStudents(currentClass);
                    renderStudentTable();
                    updateStats();
                });
            });
            
            // 搜索功能
            searchInput.addEventListener('input', () => {
                renderStudentTable();
            });
            
            // 刷新数据
            refreshBtn.addEventListener('click', async () => {
                students = await fetchStudents(currentClass);
                renderStudentTable();
                updateStats();
            });
            
            // 添加学生
            addStudentBtn.addEventListener('click', () => {
                editingStudent = null;
                modalTitle.textContent = '添加学生';
                studentForm.reset();
                studentModal.style.display = 'flex';
            });
            
            // 关闭模态框
            closeModal.addEventListener('click', () => {
                studentModal.style.display = 'none';
            });
            
            cancelBtn.addEventListener('click', () => {
                studentModal.style.display = 'none';
            });
            
            // 表单提交
            studentForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                
                const studentId = document.getElementById('studentId').value;
                const studentName = document.getElementById('studentName').value;
                const homepage = document.getElementById('homepage').value;
                
                const studentData = {
                    class: currentClass,
                    id: studentId,
                    name: studentName,
                    homepage: homepage
                };
                
                let success = false;
                
                if (editingStudent) {
                    // 编辑现有学生
                    success = await updateStudent(studentData);
                    if (success) {
                        // 更新本地数据
                        const index = students.findIndex(s => s.id === editingStudent.id);
                        if (index !== -1) {
                            students[index] = studentData;
                        }
                    }
                } else {
                    // 添加新学生
                    success = await addStudent(studentData);
                    if (success) {
                        // 重新从服务器获取数据以确保数据一致性
                        students = await fetchStudents(currentClass);
                    }
                }
                
                if (success) {
                    renderStudentTable();
                    updateStats();
                    studentModal.style.display = 'none';
                }
            });
        });

        // 渲染学生表格
        function renderStudentTable() {
            const searchTerm = searchInput.value.toLowerCase();
            
            // 过滤学生数据
            const filteredStudents = students.filter(student => 
                student.id.toLowerCase().includes(searchTerm) || 
                student.name.toLowerCase().includes(searchTerm)
            );
            
            // 清空表格
            studentTableBody.innerHTML = '';
            
            if (filteredStudents.length === 0) {
                studentTableBody.innerHTML = '<tr><td colspan="4" class="loading">没有找到匹配的学生</td></tr>';
                return;
            }
            
            // 填充表格
            filteredStudents.forEach(student => {
                const row = document.createElement('tr');
                
                row.innerHTML = `
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.homepage ? `<a href="${student.homepage}" target="_blank">查看主页</a>` : '未填写'}</td>
                    <td class="actions">
                        <button class="action-btn edit-btn" data-id="${student.id}">编辑</button>
                        <button class="action-btn delete-btn" data-id="${student.id}">删除</button>
                    </td>
                `;
                
                studentTableBody.appendChild(row);
            });
            
            // 添加编辑和删除事件监听器
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const studentId = btn.getAttribute('data-id');
                    editingStudent = students.find(s => s.id === studentId);
                    
                    if (editingStudent) {
                        modalTitle.textContent = '编辑学生';
                        document.getElementById('studentId').value = editingStudent.id;
                        document.getElementById('studentId').readOnly = true; // 编辑时学号不可修改
                        document.getElementById('studentName').value = editingStudent.name;
                        document.getElementById('homepage').value = editingStudent.homepage || '';
                        studentModal.style.display = 'flex';
                    }
                });
            });
            
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', async () => {
                    const studentId = btn.getAttribute('data-id');
                    if (confirm('确定要删除这名学生吗？此操作不可撤销。')) {
                        const success = await deleteStudent(studentId, currentClass);
                        if (success) {
                            // 从本地数据中移除
                            students = students.filter(s => s.id !== studentId);
                            renderStudentTable();
                            updateStats();
                        }
                    }
                });
            });
        }

        // 更新统计信息
        function updateStats() {
            const total = students.length;
            const withHomepage = students.filter(s => s.homepage).length;
            const withoutHomepage = total - withHomepage;
            
            totalStudentsEl.textContent = total;
            withHomepageEl.textContent = withHomepage;
            withoutHomepageEl.textContent = withoutHomepage;
        }
    </script>
</body>
</html>